package cn.stylefeng.guns.modular.gridsystem.tcp.VobrateTcp;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.json.JSONUtil;
import cn.stylefeng.guns.modular.gridsystem.websocket.WebSocketGatewayServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Random;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @Author: yuJiYuan
 * @Description: TODO
 * @DateTime: 2023/11/6 10:56
 **/
@Slf4j
//@Configuration
public class V_Test {

    @Autowired
    private static WebSocketGatewayServer webSocketGatewayServer = new WebSocketGatewayServer();
    public static Boolean isRun = false;
    public static Boolean isSendDate = true;
    private static final CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
    public static void start(){
        //isSendDate = true;
        log.info("#启动模拟方法");
        log.info("isRun->" + isRun);
        if (isRun) {
            return;
        }
        while (isSendDate) {
            if (!isRun) {
                isRun = true;
            }
            Random rand = new Random();
            double randomNum = 0.3 + 0.5 * rand.nextFloat();
            list.add(randomNum+"");
            //通过websocket发送给前端，每次先发完之后删除前10个，加入新数据
            //log.info("list.size()->"+list.size());
            if (list.size()>400) {
                String s2 = JSONUtil.toJsonStr(list);
                ThreadUtil.execAsync(()->{
                    try {
                        webSocketGatewayServer.sendVibrationMessage(s2);
                        log.info("ws发送振动消息成功");
                    } catch (IOException e) {
                        log.error("ws发送振动消息失败:{}",e.toString());
                    }
                });
                //List<String> list1 = EchoServer.list.subList(300, EchoServer.list.size());
                //EchoServer.list.removeAll(list1);
                for (int i = 0; i < 10; i++) {
                    list.remove(i);
                }
            }
        }
    }

    public static void stop(){
        isRun = false;
        isSendDate = false;
    }
}
